//
//  YFProfileView.m
//  project
//
//  Created by Winny Zhang on 2019/3/26.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFProfileView.h"
#import "HJLoginVC.h"
#import "HJLocationOJC.h"
#import "YFJourneyTagView.h"
#import "YFLocationManager.h"
#import "YFJourneyTagView.h"
#import "UIImage+YFExtension.h"
#import "SDWebImageManager.h"

@interface YFProfileView ()

/**
 头部背景ImageView
 */
@property (weak, nonatomic) IBOutlet UIImageView *headerBackgroundImageView;
/**
 头像ImageView
 */
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;
/**
 性别ImageView
 */
@property (weak, nonatomic) IBOutlet UIImageView *genderImageView;
/**
 姓名Label
 */
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
/**
 城市Label
 */
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
/**
 年龄Label
 */
@property (weak, nonatomic) IBOutlet UILabel *ageLabel;
/**
 职业Label
 */
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
/**
 标签View
 */
@property (weak, nonatomic) IBOutlet UIView *tagView;
@property (weak, nonatomic) IBOutlet UILabel *signLabel;

@end

@implementation YFProfileView

- (void)updateViews {
    
    for (UIView *view in self.tagView.subviews) {
        [view removeFromSuperview];
    }
    
    HJUserModel *model = [HJUserManager getUserModel];
    [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:nil];
    
    if (model.avatar.length == 0) {
        self.headerImageView.image = [UIImage imageNamed:@"img_mydongtai_defualt_avatar"];
    }
   NSURL * bgImageIconUrl = [NSURL URLWithString:model.backgroundIcon];
   if (model.backgroundIcon.length == 0) {
      bgImageIconUrl = [NSURL URLWithString:model.avatar];
   }
   
   [[SDWebImageManager sharedManager] loadImageWithURL:bgImageIconUrl options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
      if (image) {//下载完成后
         self.headerBackgroundImageView.image = [image blurryImage:image withBlurLevel:0.6];
      }
      [[SDWebImageManager sharedManager]cancelAll];
   }];
   
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    @weakify(self)
    [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        @strongify(self)
        if (self.avatarClickAction) {
            self.avatarClickAction();
        }
    }];
    [self.headerImageView addGestureRecognizer:tap];
   
   NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:model.nickName];
   NSTextAttachment *attch = [[NSTextAttachment alloc] init];
  if (model.auth) {
      attch.image = [UIImage imageNamed:@"auth"];
      attch.bounds = CGRectMake(5, -2, attch.image.size.width, attch.image.size.height);
   }
  
   NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
   [attri appendAttributedString:string];
   self.nameLabel.attributedText = attri;
   
    self.cityLabel.text = model.city.cityName;
    if (self.cityLabel.text.length == 0) {
        @weakify(self)
        [YFLocationManager.shared onceLocating:^(CLLocation * _Nullable location, AMapLocationReGeocode * _Nullable regeocode, NSString * _Nullable error) {
            @strongify(self)
            self.cityLabel.text =  regeocode.city;
        }];
    }
    self.ageLabel.text = [model.age stringByAppendingString:@"岁"];
    
    if (self.ageLabel.text.length == 0) {
        self.ageLabel.text = @"未填写年龄";
    }
    
//    self.careerLabel.text = model.vocationName;
//    if (model.vocationName.length == 0) {
//        self.careerLabel.text = @"未填写职业";
//    }
   
   self.sexLabel.text =model.sex.intValue == 1 ? @"男":@"女";
   self.genderImageView.image = model.sex.intValue == 1 ? setImage(@"ico_mine_male") : setImage(@"ico_mine_female");
   
   self.signLabel.text = model.intro.length > 0 ? model.intro : @"";
    // 设置 Tag
   
   CGFloat tagPadding = 6, tagMargin = 5;
   CGFloat tagViewWidth = self.frame.size.width;
   CGFloat allTagsWidth = 0;
   
   for (int i = 0; i < model.tagArray.count; i++) {
      NSString *tag = model.tagArray[i];
      CGSize tagSize = [tag sizeWithFont:[UIFont boldSystemFontOfSize:11] boundingSize:CGSizeMake(MAXFLOAT, self.frame.size.height)];
      CGFloat tagW = tagSize.width + tagPadding * 2;

      allTagsWidth += i > 1 ? tagW + (tagMargin * (i - 1)) : tagW;
      if (allTagsWidth > tagViewWidth) {
         allTagsWidth -= i > 1 ? tagW + (tagMargin * (i - 1)) : tagW;
         
         break;
      }
   }
   CGFloat height = IS_FULL_SCREEN ? 53 * SCREEN_WIDTH / 75 + 44 : 53 * SCREEN_WIDTH / 75;
   self.tagView.frame = CGRectMake((SCREEN_WIDTH - allTagsWidth - 20) / 2, height - 30 - 10, allTagsWidth, 30);
    YFJourneyTagView *tags = [[YFJourneyTagView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 20, 30) tags:model.tagArray sameColor:UIColor.blackColor];
    [self.tagView addSubview:tags];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupViews];
    [self updateViews];
}

- (void)setupViews {
    // 头像圆角
    [self.headerImageView rounded:(UIRectCornerAllCorners) radius:self.headerImageView.height * 0.5 borderColor:UIColor.blackColor borderWidth:1];
   
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeBackGroundImage:)];
    [self.headerBackgroundImageView addGestureRecognizer:tap];
    
}

/**
 更换背景图片
 @param gesture 单点手势
 */
-(void)changeBackGroundImage:(UITapGestureRecognizer *)gesture {
    self.changeBackgroundImageBlock();
}

-(UIImage *)coreBlurImage:(UIImage *)image withBlurNumber:(CGFloat)blur {
   CIContext *context = [CIContext contextWithOptions:nil];
   CIImage  *inputImage=[CIImage imageWithCGImage:image.CGImage];
   //设置filter
   CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
   [filter setValue:inputImage forKey:kCIInputImageKey];
   [filter setValue:@(blur) forKey: @"inputRadius"];
   //模糊图片
   CIImage *result=[filter valueForKey:kCIOutputImageKey];
   CGImageRef outImage=[context createCGImage:result fromRect:[result extent]];
   UIImage *blurImage=[UIImage imageWithCGImage:outImage];
   CGImageRelease(outImage);
   return blurImage;
}

@end
